/**
 * CPAR TOOLKIT - Compiler and Runtime for CPAR
 * Copyright (C) 2012 CPAR TOOLKIT Project Developers
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
#include <windows.h>
#include "cpar.h"

struct CPARSemaphore
{
  HANDLE          hdl;
  CPARAllocator   *allocator;
};


long CPARSemaphoreCreate( CPARAllocator *pAllocator, CPARSemaphore **pSemaphore, long cnt )
{
  CPARSemaphore  *p;

  p = (CPARSemaphore*) CPARAllocatorAlloc(pAllocator, sizeof(CPARSemaphore));
  if(NULL == p)
    return -1;

  p->hdl = CreateSemaphore(NULL, 0, cnt, NULL);
  if(INVALID_HANDLE_VALUE == p->hdl)
  {
    CPARAllocatorFree(pAllocator, p);
    return -2;
  }

  *pSemaphore = p;
  p->allocator = pAllocator;
  return 0;
}

void CPARSemaphoreLock( CPARSemaphore *pSem )
{
  DWORD dwWait;

  dwWait = WaitForSingleObject(pSem->hdl,0L);
}

void CPARSemaphoreUnlock( CPARSemaphore *pSem )
{
  ReleaseSemaphore(pSem->hdl, 1, NULL);
}

void CPARSemaphoreDestroy( CPARSemaphore *pSemaphore )
{
  CloseHandle(pSemaphore->hdl);
  CPARAllocatorFree(pSemaphore->allocator,pSemaphore);
}
